from flask import Flask, session, g, request
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_cors import CORS

from utils.jwt import verify_jwt

app = Flask(__name__)

from toutiao.settings import Config


#加载配置类
app.config.from_object(Config)

#创建SQLAlchem 实例对象
db = SQLAlchemy(app)

#创建redis连接对象
redis_cli = redis.Redis(host=Config.REDIS_HOST, port=Config.REDIS_PORT,db=Config.REDIS_DB)
app.redis_cli = redis_cli

#设置跨域 -- 课下可以看文档 来设置白名单
CORS(app)

# 3.app要注册蓝图
from apps.home import home_bp
app.register_blueprint(home_bp)



from apps.user import user_bp
app.register_blueprint(user_bp)



@app.before_request
def jwt_authentication():
    g.user_id = None
    g.is_refresh_token = False
    authorization = request.headers.get('Authorization')
    if authorization and authorization.startswith('Bearer '):
        token = authorization[7:]
        # 验证token
        payload = verify_jwt(token)
        if payload:
            g.user_id = payload.get('user_id')
            # 刷新token
            g.is_refresh_token = payload.get('refresh')




